package com.zy.ems.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zy.ems.common.base.BaseController;
import com.zy.ems.common.exception.ApiException;
import com.zy.ems.common.exception.BaseErrorStatus;
import com.zy.ems.common.page.PaginationResult;
import com.zy.ems.common.util.DateUtil;
import com.zy.ems.common.util.JsonUtils;
import com.zy.ems.common.util.ResultTool;
import com.zy.ems.common.util.StringUtils;
import com.zy.ems.common.util.TokenUtils;
import com.zy.ems.model.QuestionEntity;
import com.zy.ems.service.QuestionService;
import com.zy.ems.utils.enums.Constant;
import com.zy.ems.utils.enums.UserTypeEnum;
import com.zy.ems.utils.exceptions.UserCode;

@RestController
@RequestMapping("/question")
public class QuestionController extends BaseController {

    @Autowired
    private QuestionService questionService;

    @RequestMapping(value = "/getQuestionList.json", method = RequestMethod.GET)
    public Object getQuestionList(HttpServletRequest request) {
        String q = request.getParameter("q");
        String start = request.getParameter("start");
        String size = request.getParameter("size");

        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(q)) {
                paramMap = JsonUtils.readJson2Map(q, Object.class);
            }

            paramMap.put("size", size);
            paramMap.put("start", start);
            PaginationResult<QuestionEntity> data = this.questionService
                    .getQuestionList(paramMap);

            return ResultTool.success(data);
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    @RequestMapping(value = "/delQuestion.json", method = RequestMethod.POST)
    public Object deleteQuestion(HttpServletRequest request) {
        String userId = StringUtils
                .parseStr(request.getParameter(Constant.USERID));
        String mobile = StringUtils
                .parseStr(request.getParameter(Constant.MOBILE));
        String accessToken = StringUtils
                .parseStr(request.getParameter(Constant.ACCESS_TOKE));
        String qIds = StringUtils.parseStr(request.getParameter("qIds"));

        if (StringUtils.isEmpty(qIds)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            boolean access = TokenUtils.checkToken(userId, mobile, accessToken,
                    UserTypeEnum.USER);
            if (!access) {
                return ResultTool.error(UserCode.B_USER_2005);
            }

            List<Integer> ids = new ArrayList<>();
            String[] q = qIds.split(",");

            for (String id : q) {
                if (StringUtils.isEmpty(id)) {
                    continue;
                }

                ids.add(StringUtils.parseInt(id));
            }

            this.questionService.deleteQuestion(ids);

            return ResultTool.success();
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    /**
     * 增加试题
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/addQuestion.json", method = RequestMethod.POST)
    public Object addQuestion(HttpServletRequest request) {
        String question = StringUtils
                .parseStr(request.getParameter("question"));
        String userId = StringUtils
                .parseStr(request.getParameter(Constant.USERID));
        String mobile = StringUtils
                .parseStr(request.getParameter(Constant.MOBILE));
        String accessToken = StringUtils
                .parseStr(request.getParameter(Constant.ACCESS_TOKE));

        try {
            boolean access = TokenUtils.checkToken(userId, mobile, accessToken,
                    UserTypeEnum.USER);

            if (!access) {
                return ResultTool.error(UserCode.B_USER_2005);
            }

            if (StringUtils.isEmpty(question)) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            QuestionEntity entity = JsonUtils.readJson2Entity(question,
                    QuestionEntity.class);

            if (entity == null) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            entity.setCreateTime(DateUtil.nowTimeStamp());
            entity.setUpdateTime(DateUtil.nowTimeStamp());

            this.questionService.save(entity);

            return ResultTool.success(entity);
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }
}
